package user_service

import (
	"shimmer/neusoft_club_backend/controllers/utils"
	"shimmer/neusoft_club_backend/dao/domain"
	"shimmer/neusoft_club_backend/services"
	"time"
)

type UpdateUserInfoMutation struct {
	Name     *string            `json:"name,omitempty" form:"name"`
	Nickname *string            `json:"nickname,omitempty" form:"nickname"`
	Gender   *domain.UserGender `json:"gender,omitempty" form:"gender"`
	Birthday *time.Time         `json:"birthday,omitempty" form:"birthday"`
	Email    *string            `json:"email,omitempty" form:"email"`
	QQ       *string            `json:"qq,omitempty" form:"qq"`
	Wechat   *string            `json:"wechat,omitempty" form:"wechat"`
	Comment  *string            `json:"comment,omitempty" form:"comment"`
}

func (u *UpdateUserInfoMutation) ToMap() (res map[string]interface{}) {
	res = make(map[string]interface{})
	if u.Name != nil {
		res["name"] = u.Name
	}
	if u.Nickname != nil {
		res["nickname"] = u.Nickname
	}
	if u.Gender != nil {
		res["gender"] = u.Gender
	}
	if u.Birthday != nil {
		res["birthday"] = u.Birthday
	}
	if u.Email != nil {
		res["email"] = u.Email
	}
	if u.Wechat != nil {
		res["wechat"] = u.Wechat
	}
	if u.QQ != nil {
		res["qq"] = u.QQ
	}
	if u.Comment != nil {
		res["comment"] = u.Comment
	}
	return
}

func FindUserByID(id int64) (user *domain.User, err error) {
	user = &domain.User{ID: id}
	err = services.DBEngine.Model(user).Joins(domain.UserFieldAvatar).First(user).Error
	return
}

func GetUserRoles(id int64) (role domain.AuthorizationRole, err error) {
	actors := make([]*domain.UserActor, 0)
	err = services.DBEngine.Find(&actors).Where("user_id=?", id).Error
	for _, userActor := range actors {
		role.Add(userActor.Role)
	}
	return
}
func GetUserRolesForClub(userID int64, clubID int64) (role domain.AuthorizationRole, err error) {
	actors := make([]*domain.UserActor, 0)
	err = services.DBEngine.Find(&actors).Where("user_id=? and club_id=?", userID, clubID).Error
	for _, userActor := range actors {
		role.Add(userActor.Role)
	}
	return
}

func DeleteUserByID(id int64) (err error) {
	user := &domain.User{ID: id}
	err = services.DBEngine.Delete(user).Error
	return
}

func UpdateUser(userID int64, uploadMutation *UpdateUserInfoMutation) (err error) {
	err = services.DBEngine.Model(&domain.User{}).Where("id=?", userID).Updates(uploadMutation.ToMap()).Error
	return
}

func FindAllUser(where map[string]interface{},pageQuery *utils.PaginationQuery) (res utils.Pagination, err error){
	db := services.BuildWhere(where,services.DBEngine)
	db = db.Joins(domain.UserFieldAvatar,domain.UserFieldActors)
	arr := make([]*domain.User,0)
	res, err = utils.QueryAndPaginate(pageQuery,db,&arr)
	return
}
